import json
from docx import Document
from docx.oxml.ns import qn
import pdfplumber
import requests
from flask import Flask, request, jsonify, send_from_directory
import uuid
import os
import shutil


def parse_document(filepath):
    """解析 DOCX/PDF 文件内容"""
    ext = os.path.splitext(filepath)[1].lower()

    # DOCX 解析逻辑
    if ext == '.docx':
        try:
            doc = Document(filepath)
            return {
                'text': extract_paragraphs(doc),
                'styles': extract_styles(doc),
                'sections': extract_sections(doc),
                'media': extract_media(doc)
            }
        except Exception as e:
            return {'error': f'DOCX解析失败: {str(e)}'}

    # PDF 解析逻辑（基于网页17）
    elif ext == '.pdf':
        with pdfplumber.open(filepath) as pdf:
            return {
                'text': [page.extract_text() for page in pdf.pages],
                'pages': len(pdf.pages)
            }


def extract_paragraphs(doc):
    """提取段落文本"""
    return [para.text for para in doc.paragraphs]


def extract_styles(doc):
    """解析段落样式（支持中文字体）"""
    styles = []
    for para in doc.paragraphs:
        style = {
            'name': para.style.name,
            'font_size': para.style.font.size.pt if para.style.font.size else None
        }
        # 通过XML解析获取中文字体
        if para.style.element.xpath('.//w:rFonts'):
            elem = para.style.element.xpath('.//w:rFonts')[0]
            style['chinese_font'] = elem.get(qn('w:eastAsia'), None)
        styles.append(style)
    return styles


def extract_sections(doc):
    """提取节信息（使用官方API）"""
    sections = []
    for sect in doc.sections:
        sections.append({
            'page_width': sect.page_width.inches,
            'page_height': sect.page_height.inches,
            'margins': {
                'top': sect.top_margin.inches,
                'bottom': sect.bottom_margin.inches,
                'left': sect.left_margin.inches,
                'right': sect.right_margin.inches
            },
            'orientation': '横向' if sect.orientation == 1 else '纵向'
        })
    return sections


def extract_media(doc):
    """提取图片和嵌入文件"""
    media = {'images': [], 'attachments': []}

    # 提取图片
    for rel in doc.part.rels.values():
        if "image" in rel.reltype:
            media['images'].append({
                'content_type': rel.target_part.content_type,
                'blob': rel.target_part.blob
            })

    # 提取OLE嵌入对象（如压缩包）
    if hasattr(doc.part, 'related_parts'):
        for part in doc.part.related_parts.values():
            if '/oleObject' in part.partname:
                media['attachments'].append({
                    'filename': part.filename,
                    'content_type': part.content_type,
                    'blob': part.blob
                })
    return media
